import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
  state: () => ({
    user: JSON.parse(localStorage.getItem('user')) || null,
    isAuthenticated: !!localStorage.getItem('token'),
    tokenInitialized: false
  }),
  
  getters: {
    getUser: (state) => state.user,
    isLoggedIn: (state) => state.isAuthenticated,
  },
  
  actions: {
    loginUser(userData, token) {
      this.user = userData;
      this.isAuthenticated = true;
      this.tokenInitialized = true;
      
      localStorage.setItem('user', JSON.stringify(userData));
      if (token) {
        localStorage.setItem('token', token);
      }
      
      console.log('用户登录状态已更新:', userData.username);
    },
    
    registerUser(userData, token) {
      this.user = userData;
      this.isAuthenticated = true;
      this.tokenInitialized = true;
      
      localStorage.setItem('user', JSON.stringify(userData));
      if (token) {
        localStorage.setItem('token', token);
      }
      
      console.log('用户注册成功并登录:', userData.username);
    },
    
    logoutUser() {
      this.user = null;
      this.isAuthenticated = false;
      this.tokenInitialized = false;
      
      localStorage.removeItem('token');
      localStorage.removeItem('user');
      
      console.log('用户已登出');
    },
    
    updateProfile(userData) {
      this.user = { ...this.user, ...userData };
      localStorage.setItem('user', JSON.stringify(this.user));
      console.log('用户资料已更新');
    },
    
    restoreSession() {
      const userData = JSON.parse(localStorage.getItem('user'));
      const token = localStorage.getItem('token');
      
      if (userData && token) {
        this.user = userData;
        this.isAuthenticated = true;
        this.tokenInitialized = true;
        console.log('会话状态已恢复:', userData.username);
        return true;
      }
      return false;
    }
  }
}); 